package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        roleMapper.deleteRelationWithPermission(id);
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(Role entity) {
        if (entity.getId() == null) {
            roleMapper.insert(entity);
        } else {
            roleMapper.deleteRelationWithPermission(entity.getId());
            roleMapper.updateByPrimaryKey(entity);
        }
        if (entity.getPermissions() != null) {
            for (Permission permission : entity.getPermissions()) {
                roleMapper.buildRelationWithPermission(entity.getId(), permission.getId());

            }
        }
    }


    @Override
    public Role selectByPrimaryKey(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> selectAll() {
        return roleMapper.selectAll();
    }


    @Override
    public PageResult query(QueryObject qo) {
        Integer total = roleMapper.query4Count(qo);
        if (total == 0) {
            return PageResult.PAGERESULT_EMPTY;
        }
        return new PageResult(total, roleMapper.query4List(qo));
    }

    @Override
    public List<Long> getRoleByEmployeeId(Long employeeId) {
        return roleMapper.getRoleByEmployeeId(employeeId);
    }

}
